package com.fanfutian.eventproject.interceptors;

import com.fanfutian.eventproject.utils.JwtUtil;
import com.fanfutian.eventproject.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 拦截器
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 进行令牌验证，获取请求头中的token
        String token = request.getHeader("Authorization");
        try {

            // 从redis中获取token
            String redisToken  = stringRedisTemplate.opsForValue().get(token);
            if (redisToken == null) {
                throw new Exception("token不存在或失效");
            }

            // 解析token没有错误，放行
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 将解析出来的用户信息保存到ThreadLocal中
            ThreadLocalUtil.set(claims);
            log.info("令牌解析成功·········放行");
            return true;
        } catch (Exception e) {
            log.info("令牌解析失败·········拦截");
            // 令牌解析失败，修改状态吗为401
            response.setStatus(401);
            return false;
        }
    }


    /**
     * 请求处理后，清除线程变量
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //log.info("请求处理结束·········清除线程变量");
        // 清除线程变量
        ThreadLocalUtil.remove();
    }
}
